﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ScrumProject.Models;
using ScrumProject.ViewModels;
using System.Web.Security;
using System.Collections;

namespace ScrumProject.Controllers
{
    [Authorize]
    public class MyProjectsController : Controller
    {
        private SMRPO6Context db = new SMRPO6Context();
        UserRepository userR = new UserRepository();
        ProjectRepository projectR = new ProjectRepository();
        MembersRepository memberR = new MembersRepository();
        SprintRepository sprintR = new SprintRepository();
        StoryRepository storyR = new StoryRepository();
        TaskRepository taskR = new TaskRepository();
        //
        // GET: /MyProjects/

        public ActionResult Index()
        {            
            var viewModel = new ProjectIndexData();
            viewModel.Projects = memberR.GetAllProjectsOfUser(userR.GetByUsername(User.Identity.Name).Id);
            return View(viewModel);
        }

        public ActionResult Backlog()
       {
            return Backlog(new int[0]);
        }

        [HttpPost]
        public ActionResult Backlog(int[] storyNumber)
        {
            CustomPrincipal user = HttpContext.User as CustomPrincipal;
            try
            {
                int id = int.Parse(this.ControllerContext.HttpContext.Request.Cookies["projectId"].Value);
                Project project = db.Projects.Find(id);
                ViewBag.projectName = project.Name;
                ViewBag.projectDesc = project.Description;
                var viewModel = new ProjectIndexData();
                viewModel.Projects = db.Projects.Include(s => s.Stories);

                ViewBag.projectId = id;
                viewModel.Stories = viewModel.Projects.Where(i => i.Id == id).Single().Stories;
                viewModel.Sprints = viewModel.Projects.Where(i => i.Id == id).Single().Sprints;

                ViewBag.manageStories = false;
                ViewBag.manageSprints = false;
                user.Members = db.Members.Where(pr => pr.ProjectId == id).Where(pr => pr.UserId == user.UserId).FirstOrDefault();
                
                
                DateTime today = DateTime.Today;
                Sprint sprint = sprintR.GetAllSprintsByProject(id).SingleOrDefault(
                        sp => sp.DateFrom.CompareTo(today) <= 0 && sp.DateTo.CompareTo(today) >= 0);
                
                if (storyNumber.Length > 0 && sprint != null){
                    int i=0;
                    foreach(var story in viewModel.Stories){
                        if (story.Status.CompareTo("inactive  ") != 0) { continue; }
                        i++;
                        if (storyNumber.Contains(i))
                        {
                            story.SprintId = sprint.Id;
                            story.Status = "active    ";
                            db.Entry(story).State = EntityState.Modified;
                        }
                    }
                    db.SaveChanges();
                    ViewBag.nosprint = false;
                }
                else if (storyNumber.Length > 0 && sprint == null)
                {
                    ViewBag.nosprint = true;
                }
                else
                {
                    ViewBag.nosprint = false;
                }
                if (user.Members.Role.Contains("owner"))
                {
                    ViewBag.owner = true;
                }
                else
                {
                    ViewBag.owner = false;
                }
                if (user.Members.Role != "team")
                {
                    ViewBag.manageStories = true;
                    ViewBag.manageSprints = true;
                }
                return View(viewModel);
            }
            catch (NullReferenceException)
            {
                return RedirectToAction("Index");
            }
        }


        public ActionResult SaveTimeComplexity(List<TimeComplexityItem> ListComp)
        {
            //Save data
            foreach (TimeComplexityItem t in ListComp) {
                if(t.itemComplexity >= 0.0)
                    storyR.UpdateTimeComplexity(t.id, t.itemComplexity);
            }
            return Backlog(new int[0]);
        }

        public ActionResult SprintBacklog()
        {
            CustomPrincipal user = HttpContext.User as CustomPrincipal;
            try
            {
                int id = int.Parse(this.ControllerContext.HttpContext.Request.Cookies["projectId"].Value);
                Project project = db.Projects.Find(id);
                ViewBag.projectName = project.Name;
                ViewBag.projectDesc = project.Description;
                DateTime today = DateTime.Today;
                IQueryable<Story> stories;
                try
                {
                    Sprint sprint = sprintR.GetAllSprintsByProject(id).Single(
                        sp => sp.DateFrom.CompareTo(today) <= 0 && sp.DateTo.CompareTo(today) >= 0);

                    stories = storyR.GetAllStoriesBySprint(sprint.Id);
                }
                catch (System.InvalidOperationException)
                {
                    return View();
                }
                /*foreach (Story story in stories)
                {
                    story.Tasks = taskR.GetTasksByStory(story.Id).ToList();
                }*/

                ViewBag.manageStories = false;
                ViewBag.manageSprints = false;
                user.Members = db.Members.Where(pr => pr.ProjectId == id).Where(pr => pr.UserId == user.UserId).FirstOrDefault();

                if (user.Members.Role != "team")
                {
                    ViewBag.manageStories = true;
                    ViewBag.manageSprints = true;
                }
                return View(stories);
            }
            catch (NullReferenceException)
            {
                return RedirectToAction("Index");
            }
            finally
            {
            }
        }

        //Burndown Diagram not functional
        public String progressdata()
        {
            String data = "";
            try
            {
                CustomPrincipal user = HttpContext.User as CustomPrincipal;
                ViewBag.ProjectId = this.ControllerContext.HttpContext.Request.Cookies["projectId"].Value;
                int id = int.Parse(ViewBag.ProjectId);
                Project pr = projectR.GetProject(id);
                //List<RealizedWork[]> sprints = new List<RealizedWork[]>();

                /*/Sprint sprint = pr.Sprints.FirstOrDefault(sp => sp.DateFrom.CompareTo(DateTime.Today) <= 0 && sp.DateTo.CompareTo(DateTime.Today) >= 0);
                foreach (Sprint spr in pr.Sprints)//.Where<Sprint>(sp => sp.DateTo.CompareTo(DateTime.Today) < 0))
                {
                    //if (spr.RealizedWork == null)
                    {
                        List<RealizedWork> sprintRW = new List<RealizedWork>();
                        for (DateTime date = spr.DateFrom; date <= DateTime.Today && date <= spr.DateTo; date=date.AddDays(1))
                        {
                            RealizedWork rw = new RealizedWork();
                            rw.DateOfWorking = date;
                            sprintRW.Add(rw);
                        }
                        RealizedWork[] sprintRWa = sprintRW.ToArray();

                        foreach (Story story in spr.Stories)
                        {
                            foreach (Task task in story.Tasks)
                            {
                                foreach (RealizedWork rw in task.RealizedWorks.Where(rw =>
                                    rw.DateOfWorking >= spr.DateFrom && rw.DateOfWorking <= spr.DateTo))
                                {
                                    RealizedWork srw = sprintRWa[spr.DateFrom.Subtract(rw.DateOfWorking).Days];
                                    srw.WorkDone += rw.WorkDone;
                                }
                            }
                        }
                        sprints.Add(sprintRWa);
                    }
                }*/
                IQueryable<RealizedWork>[] sprints = new IQueryable<RealizedWork>[pr.Sprints.Count];

                var stories = storyR.GetAllStoriesByProject(id);
                int i = 0;
                int workDone = 0;
                var bar = projectR.GetRealizedWorkForEntireProjectInactive(id);
                var foo = projectR.GetProjectedWorkTime(id);
                double workRemaining = //(bar != null ? (double)bar : 0) +
                    (foo != null ? (double)foo : 0)*6;
                DateTime prStartD = pr.Sprints.First().DateFrom;
                foreach (Sprint spr in pr.Sprints)
                {
                    sprints[i++] = (IQueryable<RealizedWork>)sprintR.GetRealizedWorkForEntireSprint(spr.Id).Where(rw => rw.DateOfWorking.CompareTo(DateTime.Today) <= 0).Distinct();
                }
                try
                {
                    //DateTime prStartD = sprints[0].First().DateOfWorking;
                    foreach (var rw in sprints)
                    {
                        DateTime dt = prStartD.Date;
                        foreach (var day in rw)
                        {
                            for (; day.DateOfWorking.CompareTo(dt) > 0; dt = dt.AddDays(1))
                                data += dt.Subtract(prStartD).Days.ToString() + "," + workRemaining + "," + (workRemaining - workDone) + "\n";
                            if (day.DateOfWorking.CompareTo(dt) < 0)
                                continue;
                            data += dt.Subtract(prStartD).Days.ToString() + ","; //day.DateOfWorking.Subtract(prStartD).Days.ToString() + ",";
                            if (day.WorkRemaining != null)
                            {
                                workDone += day.WorkDone == null ? 0 : (int)day.WorkDone;
                                data += (/*(int)day.WorkRemaining + */workRemaining).ToString() + ",";
                                data += (/*(int)day.WorkRemaining*/  workRemaining - workDone).ToString() + "\n";
                            }
                            else
                            {
                                data += "," + workRemaining + "," + (workRemaining - workDone) + "\n";
                            }
                            dt = dt.AddDays(1);
                        }
                        data = data.Substring(0, data.Length - 1) + ",new sprint\n";
                    }
                }
                catch
                {
                }
                return data;
            }
            catch (NullReferenceException)
            {
                return "index";// RedirectToAction("Index");
            }
        }

        public ActionResult ProgressReport()
        {
            try
            {
                CustomPrincipal user = HttpContext.User as CustomPrincipal;
                ViewBag.ProjectId = this.ControllerContext.HttpContext.Request.Cookies["projectId"].Value;
                
                
                return View();
            }
            catch (NullReferenceException)
            {
                return RedirectToAction("Index");
            }
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
